#install.packages("")

library(gridExtra)
library(ggplot2)
library(Cairo)
library(foreign)
library(gtable)
library(scales)
library(data.table)
library(plyr)
library(dplyr)
library(openxlsx)
library(readstata13)
library(reshape2)
Sys.setlocale("LC_ALL", "zh_CN.UTF-8")

setwd("E:/Replication Data for Media Freedom and Public Trust in Science" ) 


listdele<-function(x){
  a<-x[complete.cases(x),]
  return(a)
}

theme_set(theme_bw() + theme(legend.position="bottom",
                             legend.direction="horizontal",
                             axis.title.x=element_text(vjust=-.5),
                             axis.text.y =  element_text(colour = "black", hjust = 0 , vjust=.5 ),
                             title=element_text(face="bold",vjust=1.5),
                             strip.text=element_text(size=13),
                             plot.title = element_text(hjust = 0.5)))


pd<-position_dodge(width=0.4)
cl<-c("steelblue","orange")

###########################################################################################
########### Figure A.4: Summary Statistics for Media Freedom Exposure (V-Dem)  ###################
###########################################################################################

##### Variations in Media Freedom Exposure (Heat Map) ########

d<-read.dta13("[F]DATA_cohort_mediafreedom(V-Dem).dta")
d$exposure<-d$Mediafreedom_VDem_GPCA

df<-expand.grid(country=unique(d$country),year=min(d$year,na.rm=T):2020,stringsAsFactors = F)


df2<-merge(df,d,by=c("country","year"),all.x=T)
df2$country<-factor(df2$country,levels=rev(unique(df2$country)))


library(RColorBrewer)

gv <- ggplot(df2, aes(x=year, y=country, fill=exposure)) +
  geom_tile(colour="black", linewidth=0.25) +  # 更新此处
  scale_fill_gradient("\n Continuous Media Freedom (V-Dem)", low="white", high="red", na.value = "grey") +
  ylab("") + xlab("Year") +
  scale_x_continuous(expand=c(0,0), breaks=seq(1930,2020,10)) +
  theme(plot.background=element_blank(),
        panel.border=element_blank(),
        axis.ticks=element_line(linewidth=0.4))


CairoPDF("[F]figure_A4.pdf",height=16,width=13)
gv
dev.off()

##############################################################################
############ Figure A.6: Estimation Results for Individual Questions  ##################
##############################################################################
library(ggstance)

dv<-read.xlsx("science_var_label.xlsx")
dv$varlab<-gsub("\\\\n","\n",dv$varlab)
dv$varlab<-factor(dv$varlab,levels=dv$varlab)
files<-dir("./result_indiQ")


dlist<-list()
for(i in 1:length(files)){
  d<-listdele(read.csv(paste("./result_indiQ/",files[i],sep=""),stringsAsFactors = F))
  ty<-substring(files[i],1,2)
  
  d$type<-ifelse(ty=="cs","Continuous Media Freedom Exposure (V-Dem)","Binary Media Freedom Exposure (V-Dem)")
  d$var<-gsub("^cs_|^ch_|\\.csv$","",files[i])
  dlist[[i]]<-d
  
}
dx<-rbindlist(dlist)

dx2<-merge(dx,dv,by.x="var",by.y="name")
dx2$edu<-factor(dx2$rn, labels=rev(c("Primary or below","Secondary","College or above")), levels = rev(c("primary","secondary","tertiary")))
dx2$type<-factor(dx2$type,levels=rev(c("Continuous Media Freedom Exposure (V-Dem)","Binary Media Freedom Exposure (V-Dem)")),labels=rev(c("Continuous Media Freedom Exposure (V-Dem)","Binary Media Freedom Exposure (V-Dem)")))
# Define colors #
col.cs<-rgb(157,157,130,maxColorValue = 255)
col.ch<-rgb(74,75,157,maxColorValue = 255)

# Plot #
gq<-ggplot(dx2,aes(x=beta,y=edu,group=type,color=type,shape=edu))+geom_pointrange(aes(xmin=lb95,xmax=ub95),position=position_dodgev(height=0.4))+facet_wrap(.~varlab,ncol=3)+xlab("")+ylab("")+
  geom_vline(xintercept=0,linetype="dotted")+
  scale_color_manual("",breaks=c("Continuous Media Freedom Exposure (V-Dem)","Binary Media Freedom Exposure (V-Dem)"),values=c("darkred", "darkblue"))+
  scale_shape_manual("",values=c(19,15,17))+
  guides(shape="none")+theme(axis.text.y = element_text(size=14),
                             legend.text = element_text(size=14))

pdf("[F]figure_A6.pdf",height=13,width=10.5)
gq
dev.off()
